const axios = require('axios');
const cloud = require('wx-server-sdk');
const crypto = require('crypto');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV, // 使用当前环境
});
const db = cloud.database();
const _ = db.command; // 初始化数据库命令对象


async function createOrder(request) {
  const { productId, quantity, schoolCode, participantId,
    payAmount, address, deliverTime,
    orderSnapshotId, printInfo, packagePickupInfos,
    imgFromCheckout, paoTuiNote, selectedService,
    // 跑腿服务手机号
    paoTuiContactPhone,
    // 跑腿任务数组（新结构）
    paoTuiTasks } = request;
  const { OPENID: userId, CLIENTIP: userIp } = cloud.getWXContext();

  try {
    // 构建orderItem对象
    const orderItem = {
      productId: productId,
      count: quantity
    };
    
    // 输入校验
    if (!orderItem || !address) {
      throw new Error('Invalid input data');
    }
    let validatedPayAmount = Number(payAmount);
    // 检查是否为有效数字
    if (isNaN(validatedPayAmount)) {
      throw new Error('Invalid payAmount: must be a number or numeric string');
    }
    if (validatedPayAmount < 0) {
      throw new Error('Invalid payAmount: must be greater than or equal to 0');
    }
    // 并发获取用户信息、商品信息和砍价信息
    const userPromise = db.collection('user').where({ out_user_id: userId }).get();
    const productPromise = db.collection('product').where({ product_id: orderItem.productId, available_address: schoolCode}).get();
    const orderSnapshotPromise = db.collection('order_snapshot').where({ _id: orderSnapshotId }).get();

    const [userInfo, productInfo, orderSnapshotInfo] = await Promise.all([userPromise, productPromise, orderSnapshotPromise]);

    // 校验用户信息
    if (userInfo.data.length === 0) throw new Error('User not found');

    // 校验商品信息
    if (productInfo.data.length === 0) throw new Error('Product not found');

    // 校验价格一致性
    const payAmountSnapshot = orderSnapshotInfo.data[0].pay_amount;
    if (payAmountSnapshot !== payAmount) {
      throw new Error('Price mismatch');
    }

    let paymentResult = null;
    const orderId = generateOrderId();

    if (payAmount > 0) {
      // 调用扫呗支付接口
      const { paymentResult: result } = await callSaoBei(userIp, userId, payAmount, schoolCode, orderItem.productId);
      paymentResult = result;

      // 校验支付结果
      if (paymentResult.data.result_code !== '01' || paymentResult.data.return_code !== '01') {
        throw new Error('Payment failed');
      }
    }

    // 保存订单
    orderItem.image_url = productInfo.data[0].image_url;
    orderItem.price = productInfo.data[0].price;
    orderItem.productTitle = productInfo.data[0].product_title;
    orderItem.imgFromCheckout = imgFromCheckout;
    await saveOrder(paymentResult, orderItem, schoolCode,
      orderId, orderSnapshotInfo, payAmount,
      address, userId, participantId,
      deliverTime, printInfo, packagePickupInfos,
      paoTuiNote, selectedService,
      // 跑腿服务手机号
      paoTuiContactPhone,
      // 跑腿任务数组
      paoTuiTasks);

    // 返回成功结果
    return {
      code: 200,
      message: 'success',
      data: payAmount > 0
        ? {
            orderId,
            nonceStr: paymentResult.data.nonceStr || '',
            package: paymentResult.data.package_str || '',
            paySign: paymentResult.data.paySign || '',
            signType: paymentResult.data.signType || '',
            timeStamp: paymentResult.data.timeStamp || '',
          }
        : { orderId },
    };
  } catch (error) {
    console.error("Error:", error.stack || error);
    return {
      code: 500,
      message: "Error processing request",
      error: error.stack || error.message
    };
  }
}

function formatDate() {
  const date = new Date();
  return date.toISOString().replace(/[-:T.]/g, '').slice(0, 14); // 格式化为 YYYYMMDDHHMMSS
}

function generateKeySign(params, accessToken) {
  delete params.key_sign;
  const sortedKeys = Object.keys(params).sort();
  const signString = sortedKeys.map((key) => `${key}=${params[key]}`).join('&');
  const stringToSign = `${signString}&access_token=${accessToken}`;
  return crypto.createHash('md5').update(stringToSign).digest('hex').toUpperCase();
}

function generateOrderId() {
  const now = new Date();
  const dateString = now.toISOString().replace(/[^0-9]/g, '').slice(2, 14); // 去掉前2位和时区
  const randomNum = Math.floor(Math.random() * 1000000).toString().padStart(6, '0'); // 生成6位随机数
  return dateString + randomNum;
}

function formatDeliverTime(deliverTime) {
  const { dayOffset, timeFrames } = deliverTime;

  // 获取当前时间并偏移日期
  const now = new Date();
  const targetDate = new Date();
  targetDate.setDate(now.getDate() + dayOffset);

  // 格式化为北京时间 yyyy-mm-dd
  const formatter = new Intl.DateTimeFormat('zh-CN', {
    timeZone: 'Asia/Shanghai', // 指定北京时间
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
  });

  // 格式化后的日期为 yyyy/mm/dd，将其替换为 yyyy-mm-dd
  const formattedDate = formatter.format(targetDate).replace(/\//g, '-');

  // 拼接日期和时间段
  return `${formattedDate} ${timeFrames}`;
}

// 从数据库中读取配置信息
async function getConfig(schoolCode, productId) {
  try {
    // 查询数据库中配置表，匹配 school_code 和 product_id
    const res = await db
      .collection('config') // 数据库集合名
      .where({
        school_code: schoolCode, // 匹配 schoolCode
        product_id: productId, // 匹配 productId
        config_name: 'subOrderConfig', // 限制 config_name
      })
      .get();

    if (!res || !res.data || res.data.length === 0) {
      console.log('配置表中未找到匹配的数据');
      return null;
    }

    // 返回查询结果的 content 数组中的第一个配置项
    const content = res.data[0]?.content;
    if (!content || content.length === 0) {
      console.error('配置内容为空');
      return null;
    }

    return content[0]; // 默认返回第一个配置项
  } catch (error) {
    console.error('查询配置表失败:', error.message);
    throw new Error('Failed to retrieve configuration');
  }
}

async function callSaoBei(userIp, userId, payAmount, schoolCode, productId) {
  // 从配置表中获取配置信息
  let config = await getConfig(schoolCode, productId);

  if (!config) {
    config = {};
    config.merchant_no = '852105331013589';
    config.terminal_id = '17089206';
    config.key_sign = 'f2b90b1c4f1c414786b82f93959b6884';
  }

  const { merchant_no, terminal_id, key_sign } = config;

  // 生成订单 ID
  const orderId = generateOrderId();

  // 构造扫呗支付参数
  const params = {
    pay_ver: '201',
    pay_type: '010',
    service_id: '010',
    merchant_no: merchant_no, // 从配置中读取
    terminal_id: terminal_id, // 从配置中读取
    terminal_ip: userIp,
    terminal_trace: orderId,
    terminal_time: formatDate(),
    total_fee: Math.round(payAmount * 100), // 转换为分
    sub_appid: 'wx187e6766fad90637',
    open_id: userId,
    key_sign: '',
  };

  // 生成签名
  params.key_sign = generateKeySign(params, key_sign); // 使用配置中的 key_sign

  // 发起支付请求
  console.log('post payment params:', JSON.stringify(params));
  try {
    const paymentResult = await axios.post(
      'http://pay.lcsw.cn/lcsw/pay/open/minipay',
      params
    );
    return { paymentResult };
  } catch (error) {
    console.error('扫呗支付接口调用失败:', error.message);
    throw new Error('Payment request failed');
  }
}


async function saveOrder(paymentResult, orderItem, schoolCode,
                         orderId, orderSnapshotInfo, payAmount,
                         address, userId, participantId,
                         deliverTime, printInfo, packagePickupInfos,
                         paoTuiNote, selectedService,
                         // 跑腿服务手机号
                         paoTuiContactPhone,
                         // 跑腿任务数组
                         paoTuiTasks) {
  const orderData = {
    order_id: orderId,
    order_item: {
      product_id: orderItem.productId,
      product_title: orderItem.productTitle,
      quantity: orderItem.count,
      image_url: orderItem.image_url,
      price: orderItem.price,
      img_from_checkout:orderItem.imgFromCheckout
    },
    // 如果printInfo不为空，赋值
    print_info: printInfo
    ? {
        file_url: printInfo.fileUrl,    
        printing_sides: printInfo.printingSides,
        printing_pages: printInfo.printingPages,
        printing_note: printInfo.printNote
      }
    : null,
    pao_tui_note: paoTuiNote,
    // 跑腿服务手机号
    pao_tui_contact_phone: paoTuiContactPhone,
    // 跑腿任务数组
    pao_tui_tasks: paoTuiTasks ? paoTuiTasks.map(task => ({
      serviceIndex: task.serviceIndex,
      optionIndex: task.optionIndex,
      serviceName: task.serviceName,
      price: task.price,
      // 新的文本字段结构
      pickupAddressText: task.pickupAddressText || '',
      pickupTimeText: task.pickupTimeText || '',
      deliveryAddressText: task.deliveryAddressText || '',
      photos: task.photos || [] // 任务图片数组
    })) : null,
    total_amount: orderSnapshotInfo.data[0].total_amount,
    discount_amount: orderSnapshotInfo.data[0].discount_amount,
    pay_amount: payAmount,
    address: {
      name: address?.name,
      phone: address?.phone,
      school: address?.school,
      detail: address?.detail,
      schoolCode: schoolCode
    },
    create_ts: new Date(),
    update_ts: new Date(),
    order_status: '待支付',
    process_status: '', // 初始状态为空，支付成功后由paySuccessCallback设置
    out_user_id: userId,
    coupon_record_id: orderSnapshotInfo.data[0].coupon_inner_id,
    participant_id: participantId || '',
    deliver_out_user_id: '', // 默认空值
    deliver_time: formatDeliverTime(deliverTime), // 所有产品都保存配送时间
    send_time: '',
    complaint_info: {}, // 默认空值
    before_cleaning_photos: [],
    after_cleaning_photos: [],
  };

    // 如果 packagePickupInfos 不为空，赋值
    if (packagePickupInfos && packagePickupInfos.length > 0) {
      orderData.package_pickup_infos = packagePickupInfos.map(info => ({
        pickup_address: info.pickupAddress,
        pickup_code: info.pickupCode,
        pickup_size: info.pickupSize,
        photos: info.photos || [], // 添加包裹图片URL数组
      }));
    }

    // 如果 selectedService 不为空，赋值
    if (selectedService && selectedService.length > 0) {
      orderData.selected_service = selectedService.map(service => ({
        selectedService: service.selectedService,
        quantity: service.quantity || 1
      }));
    }

  if (paymentResult) {
    orderData.out_trade_no = paymentResult.data.out_trade_no; // 扫呗返回的订单号
  }

  try {
    await db.collection('order').add({ data: orderData });
  } catch (error) {
    console.error('保存订单失败:', error.message);
    throw new Error('Order saving failed');
  }
}

// 跑腿专用订单保存
async function paoTuiSaveOrder(paymentResult, orderId, userId, orderItem, schoolCode, paoTuiTasks, paoTuiNote, selectedServiceConfigs, paoTuiContactPhone, payAmount) {

  const orderData = {
    order_id: orderId,
    order_item: {
      product_id: orderItem.productId,
      product_title: orderItem.productTitle,
      image_url: orderItem.imageUrl,
      price: orderItem.price
    },
    pay_amount: payAmount,
    address: {
      name: '',
      phone: paoTuiContactPhone,
      school: '',
      detail: '',
      schoolCode: schoolCode
    },
    create_ts: new Date(),
    update_ts: new Date(),
    order_status: '待支付',
    process_status: '', // 初始状态为空，支付成功后由paySuccessCallback设置
    out_user_id: userId,
    deliver_out_user_id: '', // 默认空值
    complaint_info: {}, // 默认空值
    pao_tui_tasks: paoTuiTasks || [],
    pao_tui_note: paoTuiNote || '',
    selected_service_configs: selectedServiceConfigs || {},
  };

  if (paymentResult) {
    orderData.out_trade_no = paymentResult.data.out_trade_no;
  }
  try {
    await db.collection('order').add({ data: orderData });
  } catch (error) {
    console.error('保存跑腿订单失败:', error.message);
    throw new Error('PaoTui order saving failed');
  }
}

async function paoTuiCreateOrder(request) {
  const { productId, schoolCode, paoTuiTasks, paoTuiNote, selectedServiceConfigs, paoTuiContactPhone, payAmount } = request;
  const { OPENID: userId, CLIENTIP: userIp } = cloud.getWXContext();

  try {
    let validatedPayAmount = Number(payAmount);
    if (isNaN(validatedPayAmount)) {
      throw new Error('Invalid payAmount: must be a number or numeric string');
    }
    if (validatedPayAmount < 0) {
      throw new Error('Invalid payAmount: must be greater than or equal to 0');
    }
    const orderItem = {
      productId: productId,
      imageUrl: '',
      price: '',
      productTitle: ''
    };
    // 并发获取用户信息、商品信息
    const userPromise = db.collection('user').where({ out_user_id: userId }).get();
    const productPromise = db.collection('product').where({ product_id: orderItem.productId, available_address: schoolCode}).get();
    const [userInfo, productInfo] = await Promise.all([userPromise, productPromise]);
    // 校验用户信息
    if (userInfo.data.length === 0) throw new Error('User not found');
    // 校验商品信息
    if (productInfo.data.length === 0) throw new Error('Product not found');
    let paymentResult = null;
    const orderId = generateOrderId();
    if (validatedPayAmount > 0) {
      // 调用扫呗支付接口
      const { paymentResult: result } = await callSaoBei(userIp, userId, validatedPayAmount, schoolCode, orderItem.productId);
      paymentResult = result;
      if (paymentResult.data.result_code !== '01' || paymentResult.data.return_code !== '01') {
        throw new Error('Payment failed');
      }
    }
    orderItem.imageUrl = productInfo.data[0].image_url;
    orderItem.price = productInfo.data[0].price;
    orderItem.productTitle = productInfo.data[0].product_title;
    // 保存跑腿订单
    await paoTuiSaveOrder(paymentResult, orderId, userId, orderItem, schoolCode, paoTuiTasks, paoTuiNote, selectedServiceConfigs, paoTuiContactPhone, validatedPayAmount);
    // 返回成功结果
    return {
      code: 200,
      message: 'success',
      data: validatedPayAmount > 0
        ? {
            orderId,
            nonceStr: paymentResult.data.nonceStr || '',
            package: paymentResult.data.package_str || '',
            paySign: paymentResult.data.paySign || '',
            signType: paymentResult.data.signType || '',
            timeStamp: paymentResult.data.timeStamp || '',
          }
        : { orderId },
    };
  } catch (error) {
    console.error('paoTuiCreateOrder Error:', error.stack || error);
    return {
      code: 500,
      message: 'Error processing paoTuiCreateOrder',
      error: error.stack || error.message
    };
  }
}

async function xiXieCreateOrder(request) {
  const { productId, schoolCode, address, selectedTimeInfo, serviceConfigs, imgFromCheckout, price, participantId } = request;
  const { OPENID: userId, CLIENTIP: userIp } = cloud.getWXContext();

  try {
    // 输入校验
    if (!address || !selectedTimeInfo || !serviceConfigs) {
      throw new Error('Invalid input data: address, selectedTimeInfo, and serviceConfigs are required');
    }

    // 从price对象中获取payAmount
    const payAmount = price?.payAmount;
    let validatedPayAmount = Number(payAmount);
    if (isNaN(validatedPayAmount)) {
      throw new Error('Invalid payAmount: must be a number or numeric string');
    }
    if (validatedPayAmount < 0) {
      throw new Error('Invalid payAmount: must be greater than or equal to 0');
    }

    const orderItem = {
      productId: productId,
      imageUrl: '',
      price: '',
      productTitle: ''
    };

    // 并发获取用户信息、商品信息
    const userPromise = db.collection('user').where({ out_user_id: userId }).get();
    const productPromise = db.collection('product').where({ product_id: orderItem.productId, available_address: schoolCode}).get();
    const [userInfo, productInfo] = await Promise.all([userPromise, productPromise]);

    // 校验用户信息
    if (userInfo.data.length === 0) throw new Error('User not found');
    // 校验商品信息
    if (productInfo.data.length === 0) throw new Error('Product not found');

    let paymentResult = null;
    const orderId = generateOrderId();

    if (validatedPayAmount > 0) {
      // 调用扫呗支付接口
      const { paymentResult: result } = await callSaoBei(userIp, userId, validatedPayAmount, schoolCode, orderItem.productId);
      paymentResult = result;
      if (paymentResult.data.result_code !== '01' || paymentResult.data.return_code !== '01') {
        throw new Error('Payment failed');
      }
    }

    orderItem.imageUrl = productInfo.data[0].image_url;
    orderItem.price = productInfo.data[0].price;
    orderItem.productTitle = productInfo.data[0].product_title;

    // 保存洗鞋订单
    await xiXieSaveOrder(paymentResult, orderId, userId, orderItem, schoolCode, address, selectedTimeInfo, serviceConfigs, imgFromCheckout, validatedPayAmount, participantId);

    // 返回成功结果
    return {
      code: 200,
      message: 'success',
      data: validatedPayAmount > 0
        ? {
            orderId,
            nonceStr: paymentResult.data.nonceStr || '',
            package: paymentResult.data.package_str || '',
            paySign: paymentResult.data.paySign || '',
            signType: paymentResult.data.signType || '',
            timeStamp: paymentResult.data.timeStamp || '',
          }
        : { orderId },
    };
  } catch (error) {
    console.error('xiXieCreateOrder Error:', error.stack || error);
    return {
      code: 500,
      message: 'Error processing xiXieCreateOrder',
      error: error.stack || error.message
    };
  }
}

async function kuaiDiCreateOrder(request) {
  const { productId, schoolCode, address, selectedTimeInfo, serviceConfigs, imgFromCheckout, price, participantId, pickupInputs } = request;
  const { OPENID: userId, CLIENTIP: userIp } = cloud.getWXContext();

  try {
    // 输入校验
    if (!address || !selectedTimeInfo || !serviceConfigs) {
      throw new Error('Invalid input data: address, selectedTimeInfo, and serviceConfigs are required');
    }

    // 从price对象中获取payAmount
    const payAmount = price?.payAmount;
    let validatedPayAmount = Number(payAmount);
    if (isNaN(validatedPayAmount)) {
      throw new Error('Invalid payAmount: must be a number or numeric string');
    }
    if (validatedPayAmount < 0) {
      throw new Error('Invalid payAmount: must be greater than or equal to 0');
    }

    const orderItem = {
      productId: productId,
      imageUrl: '',
      price: '',
      productTitle: ''
    };

    // 并发获取用户信息、商品信息
    const userPromise = db.collection('user').where({ out_user_id: userId }).get();
    const productPromise = db.collection('product').where({ product_id: orderItem.productId, available_address: schoolCode}).get();
    const [userInfo, productInfo] = await Promise.all([userPromise, productPromise]);

    // 校验用户信息
    if (userInfo.data.length === 0) throw new Error('User not found');
    // 校验商品信息
    if (productInfo.data.length === 0) throw new Error('Product not found');

    let paymentResult = null;
    const orderId = generateOrderId();

    if (validatedPayAmount > 0) {
      // 调用扫呗支付接口
      const { paymentResult: result } = await callSaoBei(userIp, userId, validatedPayAmount, schoolCode, orderItem.productId);
      paymentResult = result;
      if (paymentResult.data.result_code !== '01' || paymentResult.data.return_code !== '01') {
        throw new Error('Payment failed');
      }
    }

    orderItem.imageUrl = productInfo.data[0].image_url;
    orderItem.price = productInfo.data[0].price;
    orderItem.productTitle = productInfo.data[0].product_title;

    // 保存快递代取订单
    await kuaiDiSaveOrder(paymentResult, orderId, userId, orderItem, schoolCode, address, selectedTimeInfo, serviceConfigs, imgFromCheckout, validatedPayAmount, participantId, pickupInputs);

    // 返回成功结果
    return {
      code: 200,
      message: 'success',
      data: validatedPayAmount > 0
        ? {
            orderId,
            nonceStr: paymentResult.data.nonceStr || '',
            package: paymentResult.data.package_str || '',
            paySign: paymentResult.data.paySign || '',
            signType: paymentResult.data.signType || '',
            timeStamp: paymentResult.data.timeStamp || '',
          }
        : { orderId },
    };
  } catch (error) {
    console.error('kuaiDiCreateOrder Error:', error.stack || error);
    return {
      code: 500,
      message: 'Error processing kuaiDiCreateOrder',
      error: error.stack || error.message
    };
  }
}

// 洗鞋专用订单保存
async function xiXieSaveOrder(paymentResult, orderId, userId, orderItem, schoolCode, address, selectedTimeInfo, serviceConfigs, imgFromCheckout, payAmount, participantId) {
  const orderData = {
    order_id: orderId,
    order_item: {
      product_id: orderItem.productId,
      product_title: orderItem.productTitle,
      image_url: orderItem.imageUrl,
      price: orderItem.price
    },
    pay_amount: payAmount,
    address: {
      name: address?.name,
      phone: address?.phone,
      school: address?.school,
      detail: address?.detail,
      schoolCode: schoolCode
    },
    create_ts: new Date(),
    update_ts: new Date(),
    order_status: '待支付',
    process_status: '', // 初始状态为空，支付成功后由paySuccessCallback设置
    out_user_id: userId,
    participant_id: participantId || '',
    deliver_out_user_id: '', // 默认空值
    deliver_time: formatDeliverTime(selectedTimeInfo), // 格式化配送时间
    send_time: '',
    complaint_info: {}, // 默认空值
    before_cleaning_photos: imgFromCheckout || [], // 洗鞋前的照片
    after_cleaning_photos: [], // 洗鞋后的照片
    selected_service_configs: serviceConfigs || [], // 选择的服务配置
  };

  if (paymentResult) {
    orderData.out_trade_no = paymentResult.data.out_trade_no;
  }

  try {
    await db.collection('order').add({ data: orderData });
  } catch (error) {
    console.error('保存洗鞋订单失败:', error.message);
    throw new Error('XiXie order saving failed');
  }
}

// 快递代取专用订单保存
async function kuaiDiSaveOrder(paymentResult, orderId, userId, orderItem, schoolCode, address, selectedTimeInfo, serviceConfigs, imgFromCheckout, payAmount, participantId, pickupInputs) {
  // serviceConfigs按数量铺平
  let flatServiceList = [];
  if (Array.isArray(serviceConfigs)) {
    serviceConfigs.forEach(cfg => {
      const qty = cfg.quantity || 1;
      for (let i = 0; i < qty; i++) {
        flatServiceList.push(cfg.selectedService ? cfg.selectedService.name : '');
      }
    });
  }
  // 转换pickupInputs为package_pickup_infos
  let package_pickup_infos = [];
  if (Array.isArray(pickupInputs)) {
    package_pickup_infos = pickupInputs.map((item, idx) => {
      return {
        photos: item.photos || [],
        pickup_address: item.stationName || '',
        pickup_code: item.code || '',
        pickup_size: flatServiceList[idx] || ''
      };
    });
  }
  const orderData = {
    order_id: orderId,
    order_item: {
      product_id: orderItem.productId,
      product_title: orderItem.productTitle,
      image_url: orderItem.imageUrl,
      price: orderItem.price
    },
    pay_amount: payAmount,
    address: {
      name: address?.name,
      phone: address?.phone,
      school: address?.school,
      detail: address?.detail,
      schoolCode: schoolCode
    },
    create_ts: new Date(),
    update_ts: new Date(),
    order_status: '待支付',
    process_status: '', // 初始状态为空，支付成功后由paySuccessCallback设置
    out_user_id: userId,
    participant_id: participantId || '',
    deliver_out_user_id: '', // 默认空值
    deliver_time: formatDeliverTime(selectedTimeInfo), // 格式化配送时间
    send_time: '',
    complaint_info: {}, // 默认空值
    before_cleaning_photos: imgFromCheckout || [], // 下单时上传的照片
    after_cleaning_photos: [],
    selected_service_configs: serviceConfigs || [], // 选择的服务配置
    package_pickup_infos: package_pickup_infos // 包裹信息
  };

  if (paymentResult) {
    orderData.out_trade_no = paymentResult.data.out_trade_no;
  }

  try {
    await db.collection('order').add({ data: orderData });
  } catch (error) {
    console.error('保存快递代取订单失败:', error.message);
    throw new Error('KuaiDi order saving failed');
  }
}

// 零食订单创建
async function snacksCreateOrder(request) {
  const { productId, schoolCode, buildingCode, buildingName, address, deliveryTime, items, totalPrice, deliveryFee, finalPrice } = request;
  const { OPENID: userId, CLIENTIP: userIp } = cloud.getWXContext();

  try {
    // 输入校验
    if (!productId || !schoolCode || !buildingCode || !buildingName || !address || !items || items.length === 0) {
      throw new Error('Invalid input data: productId, schoolCode, buildingCode, buildingName, address, and items are required');
    }

    // 验证支付金额
    let validatedPayAmount = Number(finalPrice);
    if (isNaN(validatedPayAmount)) {
      throw new Error('Invalid finalPrice: must be a number or numeric string');
    }
    if (validatedPayAmount < 0) {
      throw new Error('Invalid finalPrice: must be greater than or equal to 0');
    }

    // 并发获取用户信息和商品信息
    const userPromise = db.collection('user').where({ out_user_id: userId }).get();
    const productPromise = db.collection('product').where({ product_id: productId, available_address: schoolCode }).get();
    const [userInfo, productInfo] = await Promise.all([userPromise, productPromise]);

    // 校验用户信息
    if (userInfo.data.length === 0) throw new Error('User not found');
    
    // 校验商品信息
    if (productInfo.data.length === 0) throw new Error('Product not found');

    let paymentResult = null;
    const orderId = generateOrderId();

    if (validatedPayAmount > 0) {
      // 调用扫呗支付接口
      const { paymentResult: result } = await callSaoBei(userIp, userId, validatedPayAmount, schoolCode, productId);
      paymentResult = result;
      if (paymentResult.data.result_code !== '01' || paymentResult.data.return_code !== '01') {
        throw new Error('Payment failed');
      }
    }

    // 保存零食订单
    await snacksSaveOrder(paymentResult, orderId, userId, productInfo.data[0], schoolCode, buildingCode, buildingName, address, deliveryTime, items, totalPrice, deliveryFee, validatedPayAmount);

    // 返回成功结果
    return {
      code: 200,
      message: 'success',
      data: validatedPayAmount > 0
        ? {
            orderId,
            nonceStr: paymentResult.data.nonceStr || '',
            package: paymentResult.data.package_str || '',
            paySign: paymentResult.data.paySign || '',
            signType: paymentResult.data.signType || '',
            timeStamp: paymentResult.data.timeStamp || '',
          }
        : { orderId },
    };
  } catch (error) {
    console.error('snacksCreateOrder Error:', error.stack || error);
    return {
      code: 500,
      message: 'Error processing snacksCreateOrder',
      error: error.stack || error.message
    };
  }
}

// 零食专用订单保存
async function snacksSaveOrder(paymentResult, orderId, userId, productInfo, schoolCode, buildingCode, buildingName, address, deliveryTime, items, totalPrice, deliveryFee, payAmount) {
  const orderData = {
    order_id: orderId,
    order_item: {
      product_id: productInfo.product_id,
      product_title: productInfo.product_title,
      image_url: productInfo.image_url,
      price: productInfo.price,
      quantity: 1 // 计算总数量
    },
    // 零食商品列表
    snacks_items: items.map(item => ({
      sub_product_id: item.subProductId,
      product_name: item.productName,
      price: item.price,
      count: item.count,
      img_url: item.imgUrl
    })),
    total_amount: totalPrice,
    delivery_fee: deliveryFee,
    pay_amount: payAmount,
    // 地址信息（原有格式）
    address: {
      name: address.name || '',
      phone: address.phone,
      school: address.school || '',
      detail: `${address.floor}-${address.room}${address.remark ? '，备注：' + address.remark : ''}`,
      schoolCode: schoolCode
    },
    // 单独封装的地址字段
    delivery_address: {
      building_code: buildingCode,
      building_name: buildingName,
      floor: address.floor,
      room: address.room,
      contact_phone: address.phone,
      remark: address.remark || ''
    },
    create_ts: new Date(),
    update_ts: new Date(),
    order_status: '待支付',
    process_status: '', // 初始状态为空，支付成功后由paySuccessCallback设置
    out_user_id: userId,
    deliver_out_user_id: '', // 默认空值
    deliver_time: deliveryTime ? deliveryTime.value || deliveryTime : '', // 配送时间
    send_time: '',
    complaint_info: {}, // 默认空值
    before_cleaning_photos: [],
    after_cleaning_photos: [],
    delivered_photos: [],
    package_pickup_infos: [],
    print_info: null
  };

  if (paymentResult) {
    orderData.out_trade_no = paymentResult.data.out_trade_no;
  }

  try {
    await db.collection('order').add({ data: orderData });
  } catch (error) {
    console.error('保存零食订单失败:', error.message);
    throw new Error('Snacks order saving failed');
  }
}

// 打印创建订单
async function printCreateOrder(request) {
  const { productId, participantId, schoolCode, address, selectedTimeInfo, serviceConfigs, imgFromCheckout, price, fileList, curPaperNum, curCopyNum, printNote } = request;
  const { OPENID: userId, CLIENTIP: userIp } = cloud.getWXContext();

  try {
    // 输入校验
    if (!address || !selectedTimeInfo || !serviceConfigs) {
      throw new Error('Invalid input data: address, selectedTimeInfo, and serviceConfigs are required');
    }

    // 从price对象中获取payAmount
    const payAmount = price?.payAmount;
    let validatedPayAmount = Number(payAmount);
    if (isNaN(validatedPayAmount)) {
      throw new Error('Invalid payAmount: must be a number or numeric string');
    }
    if (validatedPayAmount < 0) {
      throw new Error('Invalid payAmount: must be greater than or equal to 0');
    }

    const orderItem = {
      productId: productId,
      imageUrl: '',
      price: '',
      productTitle: ''
    };

    // 并发获取用户信息、商品信息
    const userPromise = db.collection('user').where({ out_user_id: userId }).get();
    const productPromise = db.collection('product').where({ product_id: orderItem.productId, available_address: schoolCode}).get();
    const [userInfo, productInfo] = await Promise.all([userPromise, productPromise]);

    // 校验用户信息
    if (userInfo.data.length === 0) throw new Error('User not found');
    // 校验商品信息
    if (productInfo.data.length === 0) throw new Error('Product not found');

    let paymentResult = null;
    const orderId = generateOrderId();

    if (validatedPayAmount > 0) {
      // 调用扫呗支付接口
      const { paymentResult: result } = await callSaoBei(userIp, userId, validatedPayAmount, schoolCode, orderItem.productId);
      paymentResult = result;
      if (paymentResult.data.result_code !== '01' || paymentResult.data.return_code !== '01') {
        throw new Error('Payment failed');
      }
    }

    orderItem.imageUrl = productInfo.data[0].image_url;
    orderItem.price = productInfo.data[0].price;
    orderItem.productTitle = productInfo.data[0].product_title;

    // 保存打印订单
    await printSaveOrder(paymentResult, orderId, userId, orderItem, schoolCode, address, selectedTimeInfo, serviceConfigs, imgFromCheckout, validatedPayAmount, participantId, fileList, curPaperNum, curCopyNum, printNote);

    // 返回成功结果
    return {
      code: 200,
      message: 'success',
      data: validatedPayAmount > 0
        ? {
            orderId,
            nonceStr: paymentResult.data.nonceStr || '',
            package: paymentResult.data.package_str || '',
            paySign: paymentResult.data.paySign || '',
            signType: paymentResult.data.signType || '',
            timeStamp: paymentResult.data.timeStamp || '',
          }
        : { orderId },
    };
  } catch (error) {
    console.error("Error:", error.stack || error);
    return {
      code: 500,
      message: "Error processing request",
      error: error.stack || error.message
    };
  }
}

// 打印专用订单保存
async function printSaveOrder(paymentResult, orderId, userId, orderItem, schoolCode, address, selectedTimeInfo, serviceConfigs, imgFromCheckout, payAmount, participantId, fileList, curPaperNum, curCopyNum, printNote) {
  // 构建打印信息，转换为老的数据库模型格式
  let printInfo = null;
  if (fileList && fileList.length > 0) {
    // 获取第一个文件作为主要文件
    const mainFile = fileList[0];
    printInfo = {
      file_url: mainFile.fileID,
      printing_note: printNote || '',
      printing_pages: curPaperNum || '1',
      printing_sides: getPrintingSides(serviceConfigs)
    };
  }

  const orderData = {
    order_id: orderId,
    order_item: {
      product_id: orderItem.productId,
      product_title: orderItem.productTitle,
      image_url: orderItem.imageUrl,
      price: orderItem.price,
      quantity: curCopyNum
    },
    pay_amount: payAmount,
    address: {
      name: address?.name,
      phone: address?.phone,
      school: address?.school,
      detail: address?.detail,
      schoolCode: schoolCode,
    },
    create_ts: new Date(),
    update_ts: new Date(),
    order_status: '待支付',
    process_status: '待打印', // 打印服务的初始状态
    out_user_id: userId,
    participant_id: participantId || '',
    deliver_out_user_id: '', // 默认空值
    deliver_time: formatDeliverTime(selectedTimeInfo), // 格式化配送时间
    send_time: '',
    complaint_info: {}, // 默认空值
    before_cleaning_photos: imgFromCheckout || [], // 下单时上传的照片
    after_cleaning_photos: [],
    selected_service_configs: serviceConfigs || [], // 选择的服务配置
    print_info: printInfo, // 打印信息
    total_amount: payAmount, // 总金额
    discount_amount: '0.0', // 折扣金额
    coupon_record_id: '', // 优惠券记录ID
  };

  if (paymentResult) {
    orderData.out_trade_no = paymentResult.data.out_trade_no;
  }

  try {
    await db.collection('order').add({ data: orderData });
  } catch (error) {
    console.error('保存打印订单失败:', error.message);
    throw new Error('Print order saving failed');
  }
}

// 根据服务配置获取打印方式
function getPrintingSides(serviceConfigs) {
  if (!serviceConfigs || serviceConfigs.length === 0) {
    return '单面打印';
  }
  
  const selectedService = serviceConfigs[0]?.selectedService;
  if (!selectedService) {
    return '单面打印';
  }
  
  // 根据服务名称判断打印方式
  const serviceName = selectedService.name;
  if (serviceName.includes('双面')) {
    return '双面打印';
  } else if (serviceName.includes('单面')) {
    return '单面打印';
  } else {
    return '单面打印'; // 默认单面打印
  }
}

// 格式化日期为扫呗退款所需格式
function formatDateForSaiBeiRefund(date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');
  return `${year}${month}${day}${hours}${minutes}${seconds}`;
}

// 封装扫呗退款逻辑
async function processRefundWithSaobei(orderId, refundFeeInCents, orderData) {
  const outTradeNo = orderData.out_trade_no;
  const schoolCode = orderData.address.schoolCode;
  const productId = orderData.order_item.product_id;

  // 如果退款金额小于等于 0，直接返回成功
  if (refundFeeInCents <= 0) {
    return {
      success: true,
      refundId: '', // 无实际退款 ID
    };
  }

   // 从配置表中获取配置信息
   let config = await getConfig(schoolCode, productId);

   if (!config) {
      config = {};
      config.merchant_no = '852105331013589';
      config.terminal_id = '17089206';
      config.key_sign = 'f2b90b1c4f1c414786b82f93959b6884';
   }
 
   const { merchant_no, terminal_id, key_sign } = config;

  // 扫呗退款参数
  const params = {
    pay_ver: '201',
    pay_type: '010',
    service_id: '030',
    merchant_no: merchant_no,
    terminal_id: terminal_id,
    terminal_trace: 'R' + orderId,
    terminal_time: formatDateForSaiBeiRefund(new Date()),
    refund_fee: refundFeeInCents, // 以分为单位的退款金额
    out_trade_no: outTradeNo,
    key_sign: ''
  };

  params.key_sign = generateKeySign(params, key_sign);

  try {
    // 调用扫呗退款接口
    const refundResult = await axios.post('http://pay.lcsw.cn/lcsw/pay/open/refund', params);
    console.log('Refund result from Saobei:', refundResult.data);

    // 检查退款结果
    if (refundResult.data.result_code === '01' && refundResult.data.return_code === '01') {
      return {
        success: true,
        refundId: refundResult.data.refundId || '', // 返回退款 ID
      };
    } else {
      return {
        success: false,
        message: refundResult.data.return_msg || 'Unknown error from Saobei',
      };
    }
  } catch (error) {
    console.error('Error occurred while processing refund with Saobei:', error);
    return {
      success: false,
      message: error.message || 'Request to Saobei failed',
    };
  }
}

// 更新优惠券数量信息
async function updateCouponQuantity(coupon_record_id) {
  if (!coupon_record_id) {
    console.log('No couponId provided, skipping coupon update.');
    return;
  }

  const couponRecord = await db.collection('coupon_record').where({ _id: coupon_record_id }).get();

  if (!couponRecord.data.length) {
    console.log('Coupon not found, skipping coupon update.');
    return;
  }

  await db.collection('coupon_record').where({ _id: coupon_record_id }).update({
    data: {
      used_quantity: couponRecord.data[0].used_quantity - 1, // 更新已使用数量
      update_ts: new Date(), // 更新时间戳
    }
  });

  console.log(`Coupon [${coupon_record_id}] updated successfully.`);
}

// 更新砍价记录状态
async function updateBargainStatus(participantId, newStatus) {
  await db.collection('bargain_record').where({
    participant_id: participantId
  }).update({
    data: {
      status: newStatus, // 更新为指定状态
      update_ts: new Date() // 更新时间戳
    }
  });
}


// 取消订单主要逻辑
async function cancelOrder(request) {
  const { orderId } = request;
  const userId = cloud.getWXContext().OPENID;

  try {
    // Validate input
    if (!orderId) {
      throw new Error('Invalid order Id');
    }

    // Fetch order data
    const orderResult = await db.collection('order').where({
      order_id: orderId
    }).get();

    if (!orderResult.data.length) {
      throw new Error('Order not found');
    }

    const orderData = orderResult.data[0];

    // 处理 `pay_amount`，确保金额计算精度
    const calculatedPayAmount = parseFloat(orderData.pay_amount); // 将字符串转为浮点数
    if (isNaN(calculatedPayAmount)) {
      throw new Error('Invalid pay_amount value');
    }

    // 获取当前已退款金额（如果不存在则默认为0）
    // 兼容历史数据：如果订单状态是已退款但没有refund_amount字段，则设置为付款金额
    let currentRefundAmount;
    if (orderData.order_status === '已退款' && !orderData.refund_amount) {
      currentRefundAmount = calculatedPayAmount;
    } else {
      currentRefundAmount = parseFloat(orderData.refund_amount || '0');
    }
    
    if (isNaN(currentRefundAmount)) {
      throw new Error('Invalid current refund amount in database');
    }

    // 计算本次退款金额（全额退款）
    const refundAmountFloat = calculatedPayAmount - currentRefundAmount;
    
    // 如果已经全额退款，则不需要再次退款
    if (refundAmountFloat <= 0) {
      return {
        code: 500,
        message: 'Order has already been fully refunded',
        data: null,
      };
    }

    const refundFeeInCents = Math.round(refundAmountFloat * 100); // 转换为整数（以分为单位)

    // 调用扫呗退款逻辑
    const refundResult = await processRefundWithSaobei(orderId, refundFeeInCents, orderData);

    if (!refundResult.success) {
        console.error('Refund failed:', refundResult);
      return {
        code: 500,
        message: refundResult.message || 'Refund failed',
        data: null,
      };
    }

    // 更新优惠券使用状态
    if (orderData.coupon_record_id) {
      await updateCouponQuantity(orderData.coupon_record_id); // 恢复优惠券数量
    }

    // 更新砍价活动状态
    if (orderData.participant_id) {
      await updateBargainStatus(orderData.participant_id, 'progressing'); // 恢复砍价活动状态为 "进行中"
    }

    // 更新订单状态
    await db.collection('order').doc(orderData._id).update({
      data: {
        order_status: '已退款', // 更新订单状态为已退款
        coupon_record_id: '', // 清空优惠券 ID
        participant_id: '', // 清空砍价活动 ID
        refund_amount: calculatedPayAmount.toString(), // 记录全额退款金额
        update_ts: new Date() // 更新时间戳
      }
    });

    return {
      code: 200,
      message: 'success',
      data: {
        refundId: refundResult.refundId, // 返回退款 ID
        refundAmount: refundAmountFloat, // 返回本次退款金额
        totalRefundAmount: calculatedPayAmount, // 返回累计退款金额（全额）
        originalPayAmount: calculatedPayAmount, // 返回原始支付金额
        orderStatus: '已退款' // 返回订单状态
      }
    };
  } catch (error) {
    console.error("Error:", error.stack || error);
    return {
      code: 500,
      message: "Error processing request",
      error: error.stack || error.message
    };
  }
}

// 处理拒绝退款
async function handleRejectRefund(request) {
  const { orderId, rejectReason } = request;

  // 参数验证 - 短路返回
  if (!orderId) {
    return { code: 400, message: "订单ID不能为空" };
  }
  
  if (!rejectReason || rejectReason.trim() === '') {
    return { code: 400, message: "拒绝原因不能为空" };
  }

  try {
    // 查询订单 - 短路返回
    const orderResult = await db.collection('order').where({
      order_id: orderId
    }).get();
    
    if (orderResult.data.length === 0) {
      return { code: 404, message: "订单不存在" };
    }

    const order = orderResult.data[0];
    
    // 订单状态验证 - 短路返回
    if (order.order_status !== '退款中') {
      return { code: 400, message: "订单当前状态不允许拒绝退款" };
    }
    
    // 确定目标订单状态 - 短路逻辑
    const targetOrderStatus = (order.process_status === '已完成') ? '已完成' : '已支付';
    
    // 更新订单信息
    const updateData = {
      order_status: targetOrderStatus,
      reject_reason: rejectReason,
      reject_time: new Date(),
      update_ts: new Date()
    };

    // 执行更新 - 短路返回
    const updateResult = await db.collection('order').doc(order._id).update({
      data: updateData
    });
    
    if (updateResult.stats.updated === 0) {
      return { code: 500, message: "数据库更新失败" };
    }

    console.log(`[handleRejectRefund] 拒绝退款成功: orderId=${orderId}, targetStatus=${targetOrderStatus}, rejectReason=${rejectReason}`);
    
    // 返回成功结果
    return {
      code: 200,
      message: "拒绝退款成功",
      data: {
        orderId: orderId,
        orderStatus: targetOrderStatus
      }
    };
    
  } catch (error) {
    console.error('[handleRejectRefund] 拒绝退款处理失败:', error);
    return {
      code: 500,
      message: "拒绝退款处理失败",
      error: error.toString()
    };
  }
}

// 更新订单状态
async function updateOrderStatus(request) {
  // 短路逻辑：如果是拒绝退款请求，直接处理并返回
  if (request.rejectRefund === true) {
    return await handleRejectRefund(request);
  }

  const { orderId, beforeCleaningPhotos, afterCleaningPhotos, processStatus, orderStatus, riderUserId, deliveredPhotos, refundReason, refundApplyTime } = request;

  // 检查必须的参数
  if (!orderId) {
    return {
      code: 400,
      message: '订单号 (orderId) 不能为空',
    };
  }

  try {
    // 先查询订单信息，检查是否已被领取
    const orderResult = await db.collection('order').where({
      order_id: orderId
    }).get();

    if (orderResult.data.length === 0) {
      return {
        code: 404,
        message: '订单不存在',
      };
    }

    const orderData = orderResult.data[0];

    // 如果是领取订单操作（传入了riderUserId），检查是否已被领取
    if (riderUserId && orderData.deliver_out_user_id) {
      return {
        code: 400,
        message: '订单已经被领取，请刷新页面',
      };
    }
    // 构造更新内容
    const updateData = {};

    // 如果有清洗前的照片，更新字段 `before_cleaning_photos`
    if (beforeCleaningPhotos) {
      updateData.before_cleaning_photos = _.push(beforeCleaningPhotos); // 添加清洗前的照片
    }

    // 如果有清洗后的照片，更新字段 `after_cleaning_photos`
    if (afterCleaningPhotos) {
      updateData.after_cleaning_photos = _.push(afterCleaningPhotos); // 添加清洗后的照片
    }

    if (deliveredPhotos) {
      updateData.delivered_photos = _.push(deliveredPhotos); // 添加交付后的照片
    }

    // 更新流程状态 `process_status`
    if (processStatus) {
      updateData.process_status = processStatus;
      if(processStatus === '已完成') {
        updateData.order_status = '已完成'
      }
    }

    // 更新订单状态 `order_status`（仅在需要时更新）
    if (orderStatus) {
      updateData.order_status = orderStatus;
    }

    // 更新退款相关信息
    if (refundReason) {
      updateData.refund_reason = refundReason;
    }

    if (refundApplyTime) {
      updateData.refund_apply_time = refundApplyTime;
    }

    if(riderUserId) {
      const riderUserPromise = db.collection('user').where({ out_user_id: riderUserId }).get();
      const [riderUserRes] = await Promise.all([riderUserPromise]);
      const riderPhone = riderUserRes?.data?.[0]?.phone;
      const riderName = riderUserRes?.data?.[0]?.nick_name;
      if (!riderPhone) {
        console.error('骑手手机号不存在');
        return {
          code: 400,
          message: '骑手手机号不能为空',
        };
      }
      updateData.deliver_out_user_id = riderUserId;
      updateData.deliver_user_phone = riderPhone;
      updateData.deliver_user_name = riderName;
    }

    // 确保有更新的数据
    if (Object.keys(updateData).length === 0) {
      console.error('没有需要更新的数据');
      return {
        code: 400,
        message: '没有需要更新的数据',
      };
    }

    // 根据订单号更新订单信息
    const result = await db.collection('order').where({ order_id: orderId }).update({
      data: updateData,
    });

    // 检查是否有匹配的订单被更新
    if (result.stats.updated === 0) {
      console.error('未找到对应的订单或数据未发生变化');
      return {
        code: 404,
        message: '未找到对应的订单或数据未发生变化',
      };
    }

    return {
      code: 200,
      message: '订单信息更新成功',
      data: updateData, // 返回更新的数据
    };
  } catch (error) {
    console.error('订单信息更新失败：', error);
    return {
      code: 500,
      message: '订单信息更新失败',
      error: error.toString(),
    };
  }
}

// 处理退款
async function processRefund(request) {
  const { orderId, refundType, refundAmount, refundReason } = request;
  
  try {
    console.log('处理退款请求:', request);
    
    // 验证输入参数
    if (!orderId || !refundType || !refundAmount) {
      throw new Error('缺少必要参数');
    }
    
    if (refundAmount <= 0) {
      throw new Error('退款金额必须大于0');
    }
    
    // 查询订单信息
    const orderResult = await db.collection('order').where({ order_id: orderId }).get();
    if (orderResult.data.length === 0) {
      throw new Error('订单不存在');
    }
    
    const order = orderResult.data[0];
    
    // 检查订单状态
    if (order.order_status === '待支付') {
      throw new Error('待支付订单无法退款');
    }
    
    if (order.order_status === '已取消') {
      throw new Error('已取消订单无法退款');
    }
    
    // 检查退款金额
    const totalAmount = parseFloat(order.pay_amount) || 0;
    if (refundAmount > totalAmount) {
      throw new Error('退款金额不能超过订单金额');
    }
    
    // 转换为分进行计算，避免浮点数精度问题
    const totalAmountInCents = Math.round(totalAmount * 100);
    const refundAmountInCents = Math.round(refundAmount * 100);
    
    // 计算累计退款金额（兼容历史数据）
    let currentRefundAmountInCents = 0;
    
    console.log('订单原始数据:', {
      order_status: order.order_status,
      refund_amount: order.refund_amount,
      refund_amount_type: typeof order.refund_amount
    });
    
    // 兼容历史数据：如果订单状态是已退款但没有refund_amount字段，则设置为付款金额
    if (order.order_status === '已退款' && (!order.refund_amount || order.refund_amount === '0')) {
      currentRefundAmountInCents = totalAmountInCents;
      console.log('使用历史数据逻辑，设置为总金额(分):', currentRefundAmountInCents);
    } else {
      const currentRefundAmount = parseFloat(order.refund_amount || '0');
      currentRefundAmountInCents = Math.round(currentRefundAmount * 100);
      console.log('从refund_amount字段读取(元):', currentRefundAmount, '转换为分:', currentRefundAmountInCents);
    }
    
    const totalRefundAmountInCents = currentRefundAmountInCents + refundAmountInCents;
    
    console.log('退款金额计算(分):', {
      currentRefundAmountInCents,
      refundAmountInCents,
      totalRefundAmountInCents,
      totalAmountInCents
    });
    
    // 检查累计退款金额不能超过订单总金额
    if (totalRefundAmountInCents > totalAmountInCents) {
      throw new Error(`累计退款金额不能超过订单金额，当前已退款：¥${(currentRefundAmountInCents / 100).toFixed(2)}，本次退款：¥${(refundAmountInCents / 100).toFixed(2)}，订单总金额：¥${(totalAmountInCents / 100).toFixed(2)}`);
    }
    
    // 更新订单状态
    const updateData = {
      refund_amount: totalRefundAmountInCents / 100, // 转换回元，保留2位小数
      refund_reason: refundReason || '',
      refund_time: new Date(),
      refund_type: refundType
    };
    
    // 兼容历史数据：如果历史数据没有refund_type字段，根据退款金额自动设置
    if (!order.refund_type && currentRefundAmountInCents > 0) {
      // 历史数据已有退款，根据退款金额判断类型
      if (currentRefundAmountInCents >= totalAmountInCents) {
        updateData.refund_type = 'full';
      } else {
        updateData.refund_type = 'partial';
      }
    }
    
    // 根据累计退款金额决定订单状态（使用分进行比较，避免浮点数精度问题）
    const isFullyRefunded = totalRefundAmountInCents >= totalAmountInCents;
    
    console.log('退款状态判断详细(分):', {
      totalRefundAmountInCents,
      totalAmountInCents,
      isFullyRefunded
    });
    
    if (isFullyRefunded) {
      // 累计退款达到或超过订单金额，标记为已退款
      updateData.order_status = '已退款';
    } else {
      // 累计退款未达到订单金额，标记为部分退款
      updateData.order_status = '部分退款';
    }
    
    console.log('最终状态设置:', {
      order_status: updateData.order_status,
    });
    
    // 调用扫呗退款接口
    const refundResult = await processRefundWithSaobei(orderId, refundAmountInCents, order);
    
    if (!refundResult.success) {
      console.error('扫呗退款失败:', refundResult);
      throw new Error(refundResult.message || '扫呗退款失败');
    }
    
    console.log('扫呗退款成功:', refundResult);
    
    // 执行更新
    await db.collection('order').where({ order_id: orderId }).update({
      data: updateData
    });
    
    console.log('退款处理成功:', {
      orderId,
      refundAmount,
      refundType,
      newStatus: updateData.order_status
    });
    
    return {
      code: 200,
      message: '退款处理成功',
      data: {
        orderId: orderId,
        refundAmount: refundAmount,
        refundType: refundType,
        orderStatus: updateData.order_status
      }
    };
    
  } catch (error) {
    console.error('退款处理失败:', error);
    return {
      code: 500,
      message: error.message || '退款处理失败',
      data: null
    };
  }
}

module.exports = {
  createOrder: createOrder,
  handleRejectRefund: handleRejectRefund,
  paoTuiCreateOrder: paoTuiCreateOrder,
  xiXieCreateOrder: xiXieCreateOrder,
  kuaiDiCreateOrder: kuaiDiCreateOrder,
  printCreateOrder: printCreateOrder,
  snacksCreateOrder: snacksCreateOrder,
  cancelOrder: cancelOrder,
  updateOrderStatus: updateOrderStatus,
  processRefund: processRefund
};